/*
Result 的 map
为了确定 Err 的类型，我们可以用 parse() 来试验
*/

use std::num::ParseIntError;

// 在下面的例子中，使用简单的 match 语句导致了更加繁琐的代码
fn multiply(first_number_str: &str, second_number_str: &str) -> Result<i32, ParseIntError> {
    match first_number_str.parse::<i32>() {
        Ok(first_number) => {
            match second_number_str.parse::<i32>() {
                Ok(second_number) => {
                    Ok(first_number * second_number)
                },
                Err(e) => Err(e),
            }
        },
        Err(e) => Err(e),
    }
}

// Option 的 map、and_then、以及很多其他组合算子也为 Result 实现了
fn multiply1(first_number_str: &str, second_number_str: &str) -> Result<i32, ParseIntError> {

    first_number_str.parse::<i32>().and_then(|first_number| {
        second_number_str.parse::<i32>().map(|second_number|first_number * second_number)
    })
}

fn print(result: Result<i32, ParseIntError>) {
    match result {
        Ok(n) => println!("n is {}", n),
        Err(e) => println!("Err: {}", e),
    }
}

fn main() {
    let twenty = multiply("10", "2");
    print(twenty);
    let twenty = multiply1("10", "2");
    print(twenty);

    // 这种情况下就会提供一条更有用的错误信息
    let tt = multiply("t", "2");
    print(tt);
    let tt = multiply1("t", "2");
    print(tt);
}